//
//  MainController01.m
//  PosApp
//
//  Created by 刘萍 on 2018/8/31.
//  Copyright © 2018年 李英新. All rights reserved.
//

#import "MainController01.h"
#import "BannerModel.h"
#import "CellModel01.h"
#import "CellModel.h"
#import "OneControllerHead01.h"
#import "OneControllerHead02.h"
#import "OneControllerCell01.h"
#import "OneControllerCell02.h"
#import "OneControllerCell03.h"
#import "OneControllerCell04.h"

#import "NewsViewController.h"
#import "XiaoFeiSQController.h"
#import "BanKaController.h"
#import "JFDuiHuanController.h"
#import "ZNHuankuanController.h"
#import "MyXYCardController.h"
#import "LingQuPosController.h"

#import "ShareController.h"
#import "PosNewsController.h"
#import "BanKaUserNewsController.h"

#import "LoginViewController.h"
#import "DYTeachingVC.h"

#import "PosApp-Swift.h"



@interface MainController01 ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,OneControllerHead01Delegate,OneControllerCell04Delegate>
@property (weak, nonatomic) IBOutlet UIView *BackView;
@property (strong, nonatomic) IBOutlet UILabel *NumbLabel;

@property (weak, nonatomic) IBOutlet UICollectionView *MainCollectView;
@property (strong, nonatomic) OneControllerHead01 * head01;
@property (strong, nonatomic) NSMutableArray * BannerArr;
@property (strong, nonatomic) NSMutableArray * PosArr;
@property (strong, nonatomic) NSMutableArray * CellArr;
@property (strong, nonatomic) NSArray * OneCellTitle;

@property (nonatomic ,strong) UIButton * jumpBtn;
@property (nonatomic ,strong) NSTimer * myTimer1;
@property (nonatomic ,strong) NSTimer * myTimer2;
@end

@implementation MainController01
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
//    [self createJumpBtn];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [self.jumpBtn removeFromSuperview];
    [self.myTimer1 invalidate];
    [self.myTimer2 invalidate];
    self.myTimer1 = nil;
    self.myTimer2 = nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.OneCellTitle = @[@"消费神器",@"办卡有奖",@"积分兑换",@"智能还款"];
    self.NumbLabel.layer.cornerRadius = self.NumbLabel.bounds.size.height/2;
    self.NumbLabel.layer.masksToBounds = YES;
    
    //   设置背景渐变色
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0,0,KScreenW,TopH);
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 1);
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:251/255.0 green:40/255.0 blue:68/255.0 alpha:1].CGColor,(__bridge id)[UIColor colorWithRed:246/255.0 green:87/255.0 blue:43/255.0 alpha:1].CGColor];
    gradientLayer.locations = @[@(0.0),@(1.0f)];
    [self.BackView.layer addSublayer:gradientLayer];
    
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    self.MainCollectView.collectionViewLayout = layout;
    self.MainCollectView.delegate = self;
    self.MainCollectView.dataSource = self;
    
    [self.MainCollectView registerNib:[UINib nibWithNibName:@"OneControllerHead01" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head01"];
    [self.MainCollectView registerNib:[UINib nibWithNibName:@"OneControllerHead02" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head02"];
    [self.MainCollectView registerNib:[UINib nibWithNibName:@"OneControllerCell01" bundle:nil] forCellWithReuseIdentifier:@"cell01"];
    [self.MainCollectView registerNib:[UINib nibWithNibName:@"OneControllerCell02" bundle:nil] forCellWithReuseIdentifier:@"cell02"];
    [self.MainCollectView registerNib:[UINib nibWithNibName:@"OneControllerCell03" bundle:nil] forCellWithReuseIdentifier:@"cell03"];
    [self.MainCollectView registerNib:[UINib nibWithNibName:@"OneControllerCell04" bundle:nil] forCellWithReuseIdentifier:@"cell04"];
    
    [self UpLoadBannerDataOfMainController01];
    [self UpLoadshopDataOfMainController01];
    
    [self UpLoadDataOfV];
//    [self createJumpBtn];
}

//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    [self createJumpBtn];
//}

- (void)createJumpBtn{
    UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(0, -60, KScreenW, 45)];
    self.jumpBtn = btn;
    btn.titleLabel.font = XHQ_FONT(15);
    btn.backgroundColor = XHQHexColor(0xfec764);
    [btn setTitle:@"智能还款全新上线啦!!!点击了解详情" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick_cc) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(start:) userInfo:nil repeats:YES];
    self.myTimer1 = myTimer;
}
- (void)btnClick_cc{
    DYTeachingVC * vc = [[DYTeachingVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)start:(NSTimer *)timer{
    [UIView animateWithDuration:0.3 animations:^{
        self.jumpBtn.frame = CGRectMake(0, kNavigationStatusHeight, KScreenW, 60);
    }];
    [timer invalidate];
    timer = nil;
    
    NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(endJumpBtn:) userInfo:nil repeats:YES];
    self.myTimer2 = myTimer;
}
-(void)endJumpBtn:(NSTimer *)timer{
    [UIView animateWithDuration:0.3 animations:^{
        self.jumpBtn.frame = CGRectMake(0, -60, KScreenW, 45);
    }];
    [timer invalidate];
    timer = nil;
}

- (void)UpLoadDataOfV{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];// app名称
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];// app版本
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"]; // app build版本
    NSLog(@"app名称 %@ app版本 %@ app build版本 %@",app_Name,app_Version,app_build);
    
//    NSString * versionCode = [app_Version stringByReplacingOccurrencesOfString:@"." withString:@""];
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:@"ios" forKey:@"type"];
    
    [MainObjectWay PostWithMethod:@"current_version" andAction:@"Version" andAddParam:YES parameters:dic success:^(id responseObject) {
        NSLog(@"版本信息= %@",responseObject);
        
        if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
            NSMutableDictionary * dic = responseObject[@"data"];
            NSString * BoildNumb = [NSString stringWithFormat:@"%@",dic[@"version_name"]];
            NSString * downStr = [NSString stringWithFormat:@"%@",dic[@"vrsion_link"]];
            if (![BoildNumb isEqual:app_build]) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"版本更新" message:@"发现新版本是否更新\n(若下载失败，请删除app后重新下载)" preferredStyle:UIAlertControllerStyleAlert];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                    
                    NSURL *cleanURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",downStr]];
                    [[UIApplication sharedApplication] openURL:cleanURL];
                    
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
                // 弹出对话框
                [self presentViewController:alert animated:true completion:nil];
            }
            
        }
        
    } failure:^(NSError *error) {
        NSLog(@"错误信息 = %@",error);
    }];
    
}

- (void)UpLoadBannerDataOfMainController01{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:@"1" forKey:@"type"];
    [dic setObject:KUseriPhone forKey:@"phone"];
    
    [MainObjectWay PostWithMethod:@"plug" andAction:@"Server" andAddParam:YES parameters:dic success:^(id responseObject) {
        NSLog(@"返回的信息 = %@",responseObject);
        if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
            NSMutableArray * arr = responseObject[@"data"][@"list"];
            for (int i = 0 ; i < arr.count; i ++) {
                NSMutableDictionary * dic = arr[i];
                BannerModel * model = [BannerModel mj_objectWithKeyValues:dic];
                [self.BannerArr addObject:model];
                
            }
            [self.head01 AddBannerImage:self.BannerArr];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"错误信息 = %@",error);
    }];
}

- (void)UpLoadshopDataOfMainController01{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:KUseriPhone forKey:@"phone"];
    
    [MainObjectWay PostWithMethod:@"groom" andAction:@"Handle" andAddParam:YES parameters:dic success:^(id responseObject) {
        NSLog(@"返回数据 = %@",responseObject);
        
        if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
            NSMutableDictionary * dic = responseObject[@"data"];
            
            NSMutableArray * arr01 = dic[@"POS"];
            for ( int i = 0; i < arr01.count; i ++) {
                NSMutableDictionary * dic = arr01[i];
                CellModel01 * model = [CellModel01 mj_objectWithKeyValues:dic];
                [self.PosArr addObject:model];
                
            }
            
            NSMutableArray * arr02 = dic[@"BANK"];
            for (int i = 0; i < arr02.count; i ++) {
                NSMutableDictionary * dic = arr02[i];
                CellModel * model = [CellModel mj_objectWithKeyValues:dic];
                [self.CellArr addObject:model];
            }
        }
        [self.MainCollectView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"错误信息 = %@",error);
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 4;
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    if (section == 2) {
        return UIEdgeInsetsMake(0, 10, 0, 10);
    }else{
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }else if (section == 1){
        return 1;
    }else if (section == 2){
        return self.PosArr.count;
    }else{
        return self.CellArr.count;
    }
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        CGFloat w = (KScreenW)/4;
        return CGSizeMake(w, 96);
    } else if (indexPath.section == 2) {
        CGFloat w = (KScreenW - 20)/2;
        return CGSizeMake(w, 100);
    } else{
        return CGSizeMake(KScreenW, 100);
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        OneControllerCell01  * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell01" forIndexPath:indexPath];
        cell.OneCell01Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"OneCell0%ld",indexPath.row +1]];
        cell.OneCell01Label.text = [NSString stringWithFormat:@"%@",self.OneCellTitle[indexPath.row]];
        return cell;
    } else if (indexPath.section == 1) {
        OneControllerCell02  * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell02" forIndexPath:indexPath];
        return cell;
    } else if (indexPath.section == 2) {
        OneControllerCell03  * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell03" forIndexPath:indexPath];
        [cell CreateOneControllerCell03];
        CellModel01 * model = self.PosArr[indexPath.row];
        [cell setModel:model];
        return cell;
    } else{
        OneControllerCell04  * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell04" forIndexPath:indexPath];
        cell.tag = indexPath.row;
        cell.delegate = self;
        [cell CreateOneControllerCell04];
        CellModel * model = self.CellArr[indexPath.row];
        [cell setModel:model];
        return cell;
    }
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                {
                    XiaoFeiSQController * XFC = [[XiaoFeiSQController alloc] init];
                    [self.navigationController pushViewController:XFC animated:YES];
                }
                break;
            case 1:
                {
                    //办卡有奖
                    
                    [self pushToBanKa];
                   
                    
                }
                break;
            case 2:
                {
                    JFDuiHuanController * JFDuiHuanC = [[JFDuiHuanController alloc] init];
                    [self.navigationController pushViewController:JFDuiHuanC animated:YES];
                }
                break;
            case 3:
                {
                    
//                    @"消费神器"
                    
                    
                    
                    VCWebView * web = [[VCWebView alloc]init];
                    NSString * token = AppContext.shared.access_token;
                    NSString * merchant = AppContext.shared.merchant;

                    NSString * memberId = AppContext.shared.member_id;

                    NSString * url = [[NSString alloc]initWithFormat: @"http://repayment.baifeidianzi.com/WebView/%@/%@/%@",merchant,token,memberId];
                    web.urlStr = url;
                    //
//                    MyXYCardController * XYCardC = [[MyXYCardController alloc] init];
                    
                    [self.navigationController pushViewController:web animated:YES];
                }
                break;
                
            default:
                break;
        }
    }else if (indexPath.section == 1){
        ShareController * shareC = [[ShareController alloc] init];
        [self.navigationController pushViewController:shareC animated:YES];
    }else if (indexPath.section == 2){
        CellModel01 * model = self.PosArr[indexPath.row];
        PosNewsController * NewsC = [[PosNewsController alloc] init];
        NewsC.PosID = model.pos_id;
        [self.navigationController pushViewController:NewsC animated:YES];
    }else{
        
    }
    
}

- (void)ClickOnBtnOfCellToBankControllerWithCellID:(NSUInteger)CellID{
    CellModel * model = self.CellArr[CellID];
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:model.bank_id forKey:@"id"];
    
    [MainObjectWay PostWithMethod:@"handle_detail" andAction:@"Handle" andAddParam:YES parameters:dic success:^(id responseObject) {
        NSLog(@"图片信息 = %@",responseObject);
        if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
            NSMutableDictionary * dicCC = responseObject[@"data"];
            
            //self.bank_pj = dic[@"bank_pj"];
            BanKaUserNewsController * BanC = [[BanKaUserNewsController alloc] init];
            BanC.BankID = model.bank_id;
            BanC.BankName = model.bank_name;
            BanC.bank_pj = dicCC[@"bank_pj"];
            [self.navigationController pushViewController:BanC animated:YES];
            
        }
        
    } failure:^(NSError *error) {
        NSLog(@"错误信息 = %@",error);
    }];
    
    
//    CellModel * model = self.CellArr[CellID];
//    BanKaUserNewsController * BanC = [[BanKaUserNewsController alloc] init];
//    BanC.BankID = model.bank_id;
//    BanC.BankName = model.bank_name;
//    BanC.bank_pj =
//    [self.navigationController pushViewController:BanC animated:YES];
}


//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return CGSizeMake(KScreenW, 200);
    } else if (section == 1) {
        return CGSizeMake(KScreenW, 0);
    } else{
        return CGSizeMake(KScreenW, 60);
    }
    
}

//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        self.head01 = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head01" forIndexPath:indexPath];
        [self.head01 CreateOneControllerHead01];
        return self.head01;
    } else {
        OneControllerHead02 * head02 = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head02" forIndexPath:indexPath];
        
       
        
        return head02;
    }
}

- (void)ClickOnBannerWithIndex:(NSUInteger)Index{
    BannerModel * model = self.BannerArr[Index];
    NSLog(@"----%@",model.plug_id);
}

- (IBAction)ClickOnLeftBtnOfMainController01:(id)sender {
    NSLog(@"提醒界面");
    NewsViewController * NewsC = [[NewsViewController alloc] init];
    [self.navigationController pushViewController:NewsC animated:YES];
//    DYTeachingVC * vc = [[DYTeachingVC alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
}





- (NSMutableArray *)BannerArr {
    if (!_BannerArr) {
        _BannerArr = [NSMutableArray array];
    }
    return _BannerArr;
}

- (NSMutableArray *)PosArr {
    if (!_PosArr) {
        _PosArr = [NSMutableArray array];
    }
    return _PosArr;
}

- (NSMutableArray *)CellArr {
    if (!_CellArr) {
        _CellArr = [NSMutableArray array];
    }
    return _CellArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)pushToBanKa{
    UIAlertController * ac = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * orginalAction = [UIAlertAction actionWithTitle:@"原有办卡通道" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        BanKaController * BKC = [[BanKaController alloc] init];
                           [self.navigationController pushViewController:BKC animated:YES];
    }];
    [ac addAction:orginalAction];
    
    UIAlertAction * newAction = [UIAlertAction actionWithTitle:@"最新办卡通道" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString * url = [NSString stringWithFormat:@"http://repayment.baifeidianzi.com/Apply/%@/%@/%@",[AppContext shared].merchant,[AppContext shared].access_token,[AppContext shared].member_id];
        
         VCWebView * web = [[VCWebView alloc]init];
        web.urlStr = url;
        
        [self.navigationController pushViewController:web animated:YES];
        
       }];
       [ac addAction:newAction];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
       [ac addAction:cancelAction];

    
    
    
    [self presentViewController:ac animated:true completion:nil];
}

@end
